<template>
  <a-dropdown :trigger="['click']" v-model="show">
    <div slot="overlay">
      <a-spin :spinning="loading">
        <a-tabs class="dropdown-tabs" :tabBarStyle="{textAlign: 'center'}" :style="{width: '297px'}">
          <a-tab-pane tab="通知" key="1">
            <a-list class="tab-pane">
              <a-list-item>
                <a-list-item-meta title="你推荐的 曲妮妮 已通过第三轮面试" description="一年前">
                  <a-avatar style="background-color: white" slot="avatar" src="https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png"/>
                </a-list-item-meta>
              </a-list-item>
              <a-list-item>
                <a-list-item-meta title="这种模板可以区分多种通知类型" description="一年前">
                  <a-avatar style="background-color: white" slot="avatar" src="https://gw.alipayobjects.com/zos/rmsportal/kISTdvpyTAhtGxpovNWd.png"/>
                </a-list-item-meta>
              </a-list-item>
            </a-list>
          </a-tab-pane>
          <a-tab-pane tab="消息" key="2">
            <a-list class="tab-pane">
              <a-list-item v-for="(item, index) in filteredChatList" :key="index">
                <a-list-item-meta :title="filteredChatList[index].num + '条消息'" :description="filteredChatList[index].time">
                  <a-avatar style="background-color: white" slot="avatar" src="https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png"/>
                </a-list-item-meta>
              </a-list-item>
            </a-list>
          </a-tab-pane>
          <a-tab-pane tab="待办" key="3">
            <a-list class="tab-pane">
              <a-list-item>
                <a-list-item-meta :title="'你收到了 '+order.num+' 份发货通知'" :description="order.time">
                  <a-avatar style="background-color: white" slot="avatar" src="https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png"/>
                </a-list-item-meta>
              </a-list-item>
              <a-list-item>
                <a-list-item-meta :title="'你收到了 '+orderafter.num+' 份售后通知'" :description="orderafter.time">
                  <a-avatar style="background-color: white" slot="avatar" src="https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png"/>
                </a-list-item-meta>
              </a-list-item>
            </a-list>
          </a-tab-pane>
        </a-tabs>
      </a-spin>
    </div>
    <span @click="fetchNotice" class="header-notice">
      <a-badge class="notice-badge" count="12">
        <a-icon :class="['header-notice-icon']" type="bell" />
      </a-badge>
    </span>
  </a-dropdown>
</template>

<script>
import axios from "axios";
export default {
  name: 'HeaderNotice',
  data () {
    return {
      loading: false,
      show: false,
      order:{
        num: 16,
        time: '12-1-1 15:15:00'
      },
      orderafter:{
        num: 16,
        time: '12-1-1 15:15:00'
      },
      ChatList:[],
    }
  },
  computed: {
    filteredChatList() {
      // 过滤掉 num 为 0 的项
      return this.ChatList.filter(item => item.num !== 0);
    }
  },
  mounted() {
    this.fetchOrdernum()
    this.fetchOrderAfterInfo()
    this.fetchChatInfo()
  },
  methods: {
    // 获取订单信息
    async fetchOrdernum() {
      try {
        const response = await axios.get(`${window.location.protocol}//${window.location.hostname}:8080/api/order/infoidOrderAll`, {
          headers: {
            Authorization: `Bearer ` + localStorage.getItem('token')
          }
        });

        if (response.data.code === 200) {
          this.order.num = response.data.data.filter(item => item.expressIs === '未发货').length
          const time =  response.data.data.filter(item => item.expressIs === '未发货').reverse()
          this.order.time = time[0].updateTime
        } else {
          console.error('获取订单信息失败:', response.data.msg);
        }
      } catch (error) {
        console.error('请求失败:', error);
      }
    },
    async fetchOrderAfterInfo() {
      try {
        const response = await axios.get(`${window.location.protocol}//${window.location.hostname}:8080/api/orderafter/infoorderafterall`, {
          headers: {Authorization: `Bearer ` + localStorage.getItem('token')}
        });
        if (response.data.code === 200) {
          this.orderafter.num = response.data.data.filter(item => item.afterStatus === '售后中').length
          const time =  response.data.data.filter(item => item.afterStatus === '售后中').reverse()
          this.orderafter.time = time[0].createTime
          console.log(response.data.data)
        }
      } catch (error) {
        console.error('请求失败:', error);
      }
    },
    async fetchChatInfo() {
      try {
        const response = await axios.get(`${window.location.protocol}//${window.location.hostname}:8080/api/messages/getAll`, {
          headers: { Authorization: `Bearer ` + localStorage.getItem('token') }
        });
        if (response.data.code === 200) {
          // 获取原始数据
          const data = response.data.data;

          // 过滤出 merchantId 不为空的项
          const filteredData = data.filter(item => item.merchantName === null);

          // 使用 reduce 对数据按 userName 分组，并统计每组的消息数量和时间
          this.ChatList = filteredData.reduce((groups, item) => {
            // 查找当前分组中是否已有相同 userName 的项
            const group = groups.find(group => group.userName === item.userName);

            if (group) {
              // 如果找到了相同的 userName，将消息数量加 1，并更新最新时间
              group.num += 1;
              group.time = item.createdTime > group.time ? item.createdTime : group.time;
            } else {
              // 如果没有找到相同的 userName，创建一个新的分组
              groups.push({
                userName: item.userName,
                num: 1,
                time: item.createdTime
              });
            }
            return groups;
          }, []);
          // 获取 localStorage 中保存的 ChatList 数据
          const storedChatList = JSON.parse(localStorage.getItem('ChatList')) || [];

          // 比对 this.ChatList 和 storedChatList，更新消息数量
          this.ChatList.forEach(chatItem => {
            const storedItem = storedChatList.find(stored => stored.userName === chatItem.userName);

            if (storedItem) {
              // 如果在 localStorage 中找到了相同的 userName，减去 localStorage 中保存的 num 值
              chatItem.num -= storedItem.num;
            }
          });

          // 打印最终分组后的结果
          console.log(this.ChatList);
        }
      } catch (error) {
        console.error('Error fetching chat info:', error);
      }
    },
    fetchNotice () {
      if (this.loading) {
        this.loading = false
        return
      }
			if (this.show) return
      this.loading = true
      setTimeout(() => {
        this.loading = false
      }, 1000)
    }
  }
}
</script>

<style lang="less">
  .header-notice{
    display: inline-block;
    transition: all 0.3s;
    span {
      vertical-align: initial;
    }
    .notice-badge{
      color: inherit;
      .header-notice-icon{
        font-size: 16px;
        padding: 4px;
      }
    }
  }
  .dropdown-tabs{
    background-color: @base-bg-color;
    box-shadow: 0 2px 8px @shadow-color;
    border-radius: 4px;
    .tab-pane{
      padding: 0 24px 12px;
      min-height: 250px;
    }
  }
</style>
